#!/usr/bin/poython3.6
# conding:utf-8
import zerorpc  # 添加模块
import threading  # 用于处理中断相关
from .msg import Messgae  # 获取消息
from .state import *
from .config import CONN_URL
from .executor import Executor
from utils import getlogger


class Conn_Manager:
    def __init__(self, timeout=3):
        self.timeout = timeout
        self.client = zerorpc.Client()
        self.event = threading.Event()
        self.message = Messgae('/var/log/mschedule/uuid')  # 此处用于初始化消息
        self.log = getlogger('agent')  # 此处填写相关的log日志名称
        self.state = WAITING
        self.exec = Executor()

    def start(self):
        try:
            self.event.clear()
            self.client.connect(CONN_URL)  # 链接处理
            self.log.info('注册消息发送 {}'.format(self.client.send(self.message.reg())))  # 发送心跳信息
            self.client.send(self.message.reg())  # 处理注册消息
            while not self.event.wait(self.timeout):  # 等待的时间
                self.log.info('心跳消息发送 {}'.format(self.client.send(self.message.hearbeat())))  # 发送心跳信息
                if self.state == WAITING:  # 如果此处是空闲状态，则进行领任务处理
                    print('获取任务task')
                    task = self.client.get_task(self.message.id)  # 此处返回三个参数，1 为taskid，二是script ，三是timeout
                    if task:  # 领取成功，则进行执行相关任务.并上传至服务器端其状态
                        self.state = RUNNING  # 此处任务成功的情况
                        code, output = self.exec.run(task[1], task[2])
                        self.client.send(self.message.result(task[0], code, output))
                        self.state = WAITING  # 状态更新为当前正常状态
                    else:
                        return "目前无消息"
        except  Exception as e:
            self.event.set()
            raise e  # 此处是抛出异常到上一级

    def shutdown(self):
        self.log.info("关闭操作")
        self.client.close()
        self.event.set()


if __name__ == "__main__":
    pass
